package com.cy.server.config.security.component;

import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @project: yeb
 *
 * @description: JwtToken工具类
 *
 * @author: LiShaoZhuo
 *
 * @create: 2021-04-26 15:00
 **/
@Component
public class JwtTokenUtil {
    private static final String CLAIM_KEY_USERNAME ="sub";
    private static final String CLAIM_KEY_CREATED ="created";
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;

    /** 
    * @Description: 根据用户信息生成token
    * @Param: userDetails
    * @return: String
    * @Author: LiShaoZhuo 
    * @Date: 2021/4/26 
    */
    public String generateToken(UserDetails userDetails){
        Map<String,Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED, new Date());
        return genereateToken(claims);
    }

    /**
    * @Description: 从token中获取用户名
    * @Param: token
    * @return:
    * @Author: LiShaoZhuo
    * @Date: 2021/4/26
    */
    public String getUserNameFromToken(String token){
        String userName;
        try {
            Claims claims = getClaimsFromToken(token);
            userName = claims.getSubject();
        } catch (Exception e) {
            userName = null;
        }
        return userName;
    }


    /**
    * @Description: 验证token是否有效
    * @Param: token,userDetails
    * @return:
    * @Author: LiShaoZhuo
    * @Date: 2021/4/26
    */
    public boolean validateToken(String token, UserDetails userDetails){
        String userName = getUserNameFromToken(token);
        return userName.equals(userDetails.getUsername()) && !isTokenExpired(token);
    }

    /**
    * @Description: 判断token是否可以被刷新，即token过期就可以被刷新
    * @Param: token
    * @return:
    * @Author: LiShaoZhuo
    * @Date: 2021/4/26
    */
    public boolean canRefresh(String token){
        return !isTokenExpired(token);
    }

    /**
    * @Description: 刷新token
    * @Param: token
    * @return:
    * @Author: LiShaoZhuo
    * @Date: 2021/4/26
    */
    public String refreshToken(String token){
        Claims claims = getClaimsFromToken(token);
        claims.put(CLAIM_KEY_CREATED, new Date());
        return genereateToken(claims);
    }
    /**
    * @Description: 验证token是否失效
    * @Param: token
    * @return:
    * @Author: LiShaoZhuo
    * @Date: 2021/4/26
    */
    private boolean isTokenExpired(String token) {
        Date expireDate = getExpiredDateFromToken(token);
        return expireDate.before(new Date());
    }

    /** 
    * @Description: 从token中获取失效时间
    * @Param: token
    * @return:  
    * @Author: LiShaoZhuo 
    * @Date: 2021/4/26 
    */
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    /**
    * @Description: 从token中获取荷载
    * @Param: token
    * @return:  
    * @Author: LiShaoZhuo 
    * @Date: 2021/4/26 
    */
    private Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return claims;
    }

    /**
    * @Description: 根据荷载生成JWT Token
    * @Param: claims
    * @return:  
    * @Author: LiShaoZhuo 
    * @Date: 2021/4/26 
    */
    private String genereateToken(Map<String,Object> claims){
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();
    }

    /** 
    * @Description: 生成token失效时间
    * @Param:  
    * @return:  
    * @Author: LiShaoZhuo 
    * @Date: 2021/4/26 
    */
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }
}
